package com.woniuxy.ticket.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.ticket.mapper.MoviesMapper;
import com.woniuxy.ticket.mapper.OrdersMapper;
import com.woniuxy.ticket.mapper.UsersMapper;
import com.woniuxy.ticket.model.dto.AddDto;
import com.woniuxy.ticket.model.entity.Movies;
import com.woniuxy.ticket.model.entity.Orders;
import com.woniuxy.ticket.model.entity.Users;
import com.woniuxy.ticket.model.vo.OrdersVo;
import com.woniuxy.ticket.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 针对表【orders】的数据库操作Service实现
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private MoviesMapper moviesMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String CACHE_KEY_PREFIX = "orders:";

    @Override
    @Cacheable(cacheNames = CACHE_KEY_PREFIX, keyGenerator = "keyGenerator")
    public Map<String, Object> getAllOrders(int pageNum, int pageSize) {
        Page<Orders> ordersPage = new Page<>(pageNum, pageSize);
        ordersMapper.selectPage(ordersPage, null);

        List<OrdersVo> ordersVoList = new ArrayList<>();
        for (Orders order : ordersPage.getRecords()) {
            OrdersVo ordersVo = new OrdersVo();
            Users user = usersMapper.selectById(order.getUserId());
            ordersVo.setUsername(user != null ? user.getUsername() : "Unknown User");
            Movies movie = moviesMapper.selectById(order.getMovieId());
            ordersVo.setTitle(movie != null ? movie.getTitle() : "Unknown Movie");
            ordersVo.setQuantity(order.getQuantity());
            ordersVo.setTotalPrice(order.getTotalPrice());
            ordersVo.setOrderDate(order.getOrderDate());
            ordersVoList.add(ordersVo);
        }

        // 构造返回结果
        Map<String, Object> response = new HashMap<>();
        response.put("data", ordersVoList);
        response.put("total", ordersPage.getTotal());
        return response;
    }

    @Override
    public String addOrder(AddDto addDto) {
        Users user = usersMapper.selectById(addDto.getUserId());
        if (user == null) {
            return "用户不存在";
        }

        Movies movie = moviesMapper.selectById(addDto.getMovieId());
        if (movie == null) {
            return "电影不存在";
        }

        BigDecimal totalPrice = movie.getPrice().multiply(new BigDecimal(addDto.getQuantity()));

        Orders order = new Orders();
        order.setUserId(addDto.getUserId());
        order.setMovieId(addDto.getMovieId());
        order.setQuantity(addDto.getQuantity());
        order.setTotalPrice(totalPrice);
        order.setOrderDate(new Date());

        int rowsInserted = ordersMapper.insert(order);

        if (rowsInserted > 0) {
            clearOrderCache();
            return "success";
        } else {
            return "添加失败";
        }
    }

    private void clearOrderCache() {
        Set<String> keys = redisTemplate.keys(CACHE_KEY_PREFIX + "*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
}
